using System;
using System.Net;

namespace HashFoo.Core
{
    /// <summary>
    /// Result object for an web request in an error state.
    /// </summary>
    public class WebRequestError
    {
        readonly HttpStatusCode? _statusCode;
        readonly string _serverResponse;
        readonly Exception _exception;

        /// <summary>
        /// Create a new <see cref="WebRequestError"/>
        /// </summary>
        /// <param name="statusCode"></param>
        /// <param name="serverResponse"></param>
        /// <param name="exception"></param>
        public WebRequestError(HttpStatusCode statusCode, string serverResponse, Exception exception = null)
        {
            _statusCode = statusCode;
            _serverResponse = serverResponse;
            _exception = exception;
        }

        /// <summary>
        /// Create a new <see cref="WebRequestError"/>
        /// </summary>
        /// <param name="serverResponse"></param>
        /// <param name="exception"></param>
        public WebRequestError(string serverResponse, Exception exception = null)
        {
            _serverResponse = serverResponse;
            _exception = exception ?? new Exception(serverResponse);
        }

        /// <summary>
        /// Create a new <see cref="WebRequestError"/>
        /// </summary>
        /// <param name="exception"></param>
        public WebRequestError(Exception exception)
        {
            _exception = exception;
        }

        /// <summary>
        /// Creates a new <see cref="WebRequestError"/> from a bad <see cref="HttpWebResponse"/> and optional exception.
        /// </summary>
        /// <param name="badResponse"></param>
        /// <param name="exception"></param>
        public WebRequestError(HttpWebResponse badResponse, Exception exception = null)
        {
            _statusCode = badResponse.StatusCode;
            _serverResponse = WebUtil.GetResponseAsString(badResponse);
            _exception = exception ?? new Exception(_serverResponse);
        }

        /// <summary>
        /// The status code returned.  Null if none (the error occured before a response was captured).
        /// </summary>
        public HttpStatusCode? StatusCode
        {
            get
            {
                return _statusCode;
            }
        }

        /// <summary>
        /// The response from the server.  Null if no response.
        /// </summary>
        public string ServerResponse
        {
            get
            {
                return _serverResponse;
            }
        }

        /// <summary>
        /// The underlying exception that caused the error.  Should not be null.
        /// </summary>
        public Exception ErrorException
        {
            get
            {
                return _exception;
            }
        }
    }
}